<?php

namespace app\command;

use app\common\model\czip\IPCZ;
use app\common\model\RegisterUser;
use app\common\model\Tools;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Exception;

class IpCity extends Command
{

    protected function configure()
    {
        $this->setName('ip_city')->setDescription('ip归属地查询');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln('ip_city');
        try {
            $user_model = new RegisterUser();
            $user_list = $user_model->where('ip_city', '')->field('id,ip')->select();
            if ($user_list) {
                foreach ($user_list as $user) {
                    $ip_city = IPCZ::czipMain($user['ip']);
                    if ($ip_city['code']) {
                        $user_model->edit(['id' => $user['id']], ['ip_city' => $ip_city['data']['country'] . '(' . ($ip_city['data']['area'] ?? '本地') . ')']);
                    } else {
                        $user_model->edit(['id' => $user['id']], ['ip_city' => '查询失败']);
                    }
                }
            }
            $output->writeln('OK');
        } catch (Exception $exception) {
            Tools::log('./ip_city.log', [$exception->getLine(), $exception->getMessage()]);
        }
    }
}
